<?php

require_once 'PipesImpl/Model.php';
require_once 'PipesImpl/Form/Element.php';

class Pipes_Form_Element implements PipesImpl_Form_Element
{
	private $_model = null;
	private $_modelName = '';
	private $_elementName = '';
	private $_properties = array();
	private $_value = null;
	
	public function __construct(PipesImpl_Model $model, $elementName) 
	{
		$this->_modelName = $model->getName();
		$this->_elementName = $elementName;
		
		$columns = $model->getColumns();
		$properties = $columns[$elementName];
		$this->_properties = $properties;
		
		if (!is_null($model->$elementName)) {
			$this->_value = $model->$elementName;
		}
	}
	
	/**
	 * @todo refactor into a Strategy pattern to implement element generation
	 */
	public function render() {
		// check to see if this should even continue processing
		if ($this->_properties->visible === false && empty($this->_value)) {
			return;
		}
		
		return $this->_generateInput();
	}

	private function _generateInput() {
		$elementId = 'form__' . $this->_modelName . '__' . $this->_elementName;
		$return = "<div>\n";
		if ($this->_properties->visible === false) {
			$value = ($this->_value != '') ? "value=\"{$this->_value}\" " : '';
			$return .= "	<input id=\"{$elementId}\" name=\"{$this->_modelName}[{$this->_elementName}]\" {$value}type=\"hidden\" maxlength=\"{$this->_properties->size}\" />\n";
			$return .= "</div>";
			return $return;
		}
		
		$return .= "	<label for=\"{$elementId}\">{$this->_properties->label}</label>\n";
		
		$attrib = '';
		
		switch ($this->_properties->type) {
		case 'SET' :
			$attrib = ' multiple="multiple"';
			// don't break - this is added to a regular select
			
		case 'ENUM' :
			$return .= "	<select id=\"{$elementId}\" name=\"{$this->_modelName}[{$this->_elementName}]\"{$attrib}>\n";
			foreach ($this->_properties->options as $option) {
				$return .= "		<option>{$option}</option>\n";
			}
			$return .= "	</select>\n";
			break;
		
		case 'TEXT' :
		case 'BLOB' :
			$return .= "	<textarea id=\"{$elementId}\" name=\"{$this->_modelName}[{$this->_elementName}]\">{$this->_value}</textarea>\n";
			break;
			
		default :
			$value = ($this->_value != '') ? "value=\"{$this->_value}\" " : '';
			$return .= "	<input id=\"{$elementId}\" name=\"{$this->_modelName}[{$this->_elementName}]\" {$value}type=\"text\" maxlength=\"{$this->_properties->size}\" />\n";
			break;
		}
		
		if ($this->_properties->required) {
			$return .= "	<div class=\"validation required\">{$this->_properties->label} is required</div>\n";
		}
		$return .= "</div>";
		return $return;
	}
}

